// 用户信息与 token 缓存封装
// 缓存策略：localStorage + 内存快取，避免频繁 JSON.parse

const USER_KEY = 'zqt:userInfo'
const TOKEN_KEY = 'token'
let _user = null
let _token = null

export const setUser = (user) => {
	if (!user || typeof user !== 'object') return
	_user = user
	try {
		localStorage.setItem(USER_KEY, JSON.stringify(user))
	} catch (e) {
		console.error('缓存用户信息失败', e)
	}
}

export const getUser = () => {
	if (_user) return _user
	const raw = localStorage.getItem(USER_KEY)
	if (!raw) return null
	try {
		_user = JSON.parse(raw)
		return _user
	} catch (e) {
		console.error('解析用户信息失败', e)
		localStorage.removeItem(USER_KEY)
		return null
	}
}

export const setToken = (token) => {
	if (!token) return
	_token = token
	try {
		localStorage.setItem(TOKEN_KEY, token)
	} catch (e) {
		console.error('缓存 token 失败', e)
	}
}

export const getToken = () => {
	if (_token) return _token
	const token = localStorage.getItem(TOKEN_KEY)
	_token = token
	return token
}

export const clearUser = () => {
	_user = null
	_token = null
	localStorage.removeItem(USER_KEY)
	localStorage.removeItem(TOKEN_KEY)
}

export default {
	setUser,
	getUser,
	setToken,
	getToken,
	clearUser,
}
